package com.cresch.ical.downloader.ical;
import java.util.ArrayList;
import java.util.Collections;

/**
 * 
 * @author Resch Christian
 *
 */
public class CalendarMapper {
	
	
	public static VCalendar stringToCalendar(String calendar) {
		VCalendar vCalendar = new VCalendar();		
		Splitter stringSplitter = new Splitter();
		ElementSplitter splitter = new ElementSplitter(stringSplitter);
		splitter.setInput(calendar);
		
		// get calendar scale
		vCalendar.setCalendarScale(splitter.singleStringElement(VCalendar.CALSCALE, VCalendar.LINESEPERATOR));		
		
		// get version
		vCalendar.setVersion(splitter.singleStringElement(VCalendar.VERSION, VCalendar.LINESEPERATOR));
		
		// get alle the event entries
		stringSplitter.Initialize(VEvent.STARTTAG, VEvent.ENDTAG);
		ArrayList<String> resultList = stringSplitter.splittUp(calendar);		
		for (int i = 0; i < resultList.size(); i++) {
			String event = resultList.get(i);
			VEvent currentEvent = EventMapper.stringToEvent(event);
			
			if (!vCalendar.eventList.containsKey(currentEvent.getId())) {
				vCalendar.eventList.put(currentEvent.getId(), currentEvent);
				vCalendar.orderdEventList.add(currentEvent);
			}
		}
		Collections.sort(vCalendar.orderdEventList, new VEventComperator());
				
		return vCalendar;
	}

}
